package com.cti.ftpservice.ftp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cti.ftpservice.ftp.CommonsFtpUtils.DownloadStatus;
import com.cti.ftpservice.vo.FtpDownLoadBaseServiceInfoVo;
import com.cti.ftpservice.vo.FtpFileInfoVo;
import com.cti.ftpservice.vo.FtpOnixXmlInfoVo;

public class FTPDownLoadXmlFiles implements  Runnable {
	private FtpOnixXmlInfoVo ftpDownLoadParams;
	private static Log logger = LogFactory.getLog(FTPDownLoadXmlFiles.class);
	public FTPDownLoadXmlFiles(FtpOnixXmlInfoVo _ftpDownLoadParams){
			ftpDownLoadParams=_ftpDownLoadParams;
		}
	public void run() {
		FtpFileInfoVo downPath=null;
		if(ftpDownLoadParams==null)
			return;
		while ((downPath=ftpDownLoadParams.getFirstDownloadFilePath())!=null) {
			try {
				 File file=new File(downPath.getLocalFtpPath());
				 boolean download=true;
				 if(file.exists()&&file.length()>=downPath.getFileSize())
					 download=false;
				 if(download){
					 FTPClientHelper ftpClient=new FTPClientHelper();
					 if(!ftpClient.isConnected())
					    CommonsFtpUtils.connect(ftpClient,ftpDownLoadParams.getFtpURL(), new java.lang.Integer(ftpDownLoadParams.getFtpport()), ftpDownLoadParams.getUsername(), ftpDownLoadParams.getPwd());
					 DownloadStatus status=CommonsFtpUtils.download(ftpClient,downPath.getFtpServicePath(),downPath.getLocalFtpPath());
					 CommonsFtpUtils.disconnect(ftpClient);
					 if(status!=DownloadStatus.Local_Bigger_Remote&&status!=DownloadStatus.Download_From_Break_Failed&&status!=DownloadStatus.Download_New_Failed)
						 logger.info(Thread.currentThread().getName()+"成功下载文件："+downPath.getFileName()+"; 已经处理"+(ftpDownLoadParams.getDealCount()+1)+"个文件");
				 }else{
					 logger.info(Thread.currentThread().getName()+"成功下载文件："+downPath.getFileName()+"; 已经处理"+(ftpDownLoadParams.getDealCount()+1)+"个文件");
				 }
				 List<FtpFileInfoVo> temp=new ArrayList<FtpFileInfoVo>();
				 temp.add(downPath);
				 //保存下载的文件信息到数据库
				 FileUtils.saveDownLoadFileInfoToDB(ftpDownLoadParams.getId(),temp,FtpDownLoadBaseServiceInfoVo.FtpServiceType_OnixDownloadFile);
				 ftpDownLoadParams.adddealItem(downPath,true);
				 if(ftpDownLoadParams.getFinished())
				 {
					 ftpDownLoadParams.stopDownLoadFiles();
				 }
				 Thread.sleep(1000);
			} catch (Exception e) {
				if(downPath!=null){
					 ftpDownLoadParams.adddealItem(downPath,false);
					 logger.error(downPath+"下载出错");
				}
				 logger.error(Thread.currentThread().getName()+e.getMessage());
			}
			Thread.yield();
		}
	}
}
